/**
 * Created by Laggo on 15/12/11.
 */
app.service('ajax', ['$q', '$http', 'SERVER_URL', 'toolService', '$state', '$sessionStorage', 'Flash',function ($q, $http, SERVER_URL, toolService, $state, $sessionStorage,Flash) {
    this.post = function (postData) {
        return this.ajax(postData, 'post')
    };
    this.get = function (postData) {
        return this.ajax(postData, 'get')
    };
    this.ajax = function (postData, method) {
        var defer = $q.defer();
        var promise = defer.promise;

        //debug
        if (postData.debug) {
            console.log(method, 'GO', postData.data, postData.url);
        }
        //
        //if(method === 'post'&&!confirm('是否操作')) {
        //    return false;
        //}
        if(method === 'post'){
            toolService.objecttoParams(postData.data);
        }

        $http({
            method: method,
            url: SERVER_URL + postData.url,
            params: postData.data,
            headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'}
        }).then(
            function success(response) {

                var data = response.data;
                var code = data.code;

                //debug
                if (postData.debug) {
                    console.log('Back', data)

                }

                if (code == 0) {
                    defer.resolve(response.data.data);
                }
                else if (code == 1002 || code == 1003) {
                    delete $sessionStorage.username;
                    $state.go("login");
                } else {
                    Flash.create('warning', data.msg, 'custom-class');
                }
            },
            function failed(response) {
                Flash.create('danger','请求异常', 'custom-class');
            }
        );
        return promise
    }
}]);
